"""
字典编辑对话框 - 统一样式版本
"""

import logging
from typing import Dict, Any, Optional
from PyQt5.QtWidgets import (
    QFormLayout, QLineEdit, QTextEdit, QSpinBox, 
    QCheckBox, QComboBox, QGroupBox, QVBoxLayout
)
from PyQt5.QtCore import Qt, pyqtSignal

from src.app.ui.base_dialog import BaseDialog
from src.app.modules.dictionary.service import DictionaryService
from src.app.modules.dictionary.utils import DictionaryUtils

logger = logging.getLogger(__name__)

class DictionaryDialog(BaseDialog):
    """字典编辑对话框 - 统一样式版本"""
    
    # 信号定义
    dictionary_saved = pyqtSignal(str)  # 字典保存信号
    
    def __init__(self, parent=None, dict_id: Optional[str] = None, parent_code: Optional[str] = None):
        self.dict_id = dict_id
        self.parent_code = parent_code
        self.service = DictionaryService()
        self.utils = DictionaryUtils()
        self.is_edit = dict_id is not None
        
        # 设置对话框标题和尺寸
        title = "编辑字典" if self.is_edit else "新增字典"
        super().__init__(parent, title=title, width=600, height=500)
        
        # 如果是编辑模式，加载数据
        if dict_id:
            self.load_dictionary_data()
    
    def create_content_widget(self):
        """创建内容区域"""
        widget = QGroupBox("字典信息")
        layout = QVBoxLayout(widget)
        
        # 表单布局
        form_layout = QFormLayout()
        form_layout.setSpacing(15)
        
        # 字典类型
        self.dict_type_combo = QComboBox()
        self.dict_type_combo.addItems([
            "asset_type", "system_type", "middleware_type", 
            "account_type", "ip_purpose", "ip_vlan", "ip_status"
        ])
        if not self.is_edit:
            form_layout.addRow("字典类型*:", self.dict_type_combo)
        
        # 字典代码
        self.dict_code_edit = QLineEdit()
        self.dict_code_edit.setPlaceholderText("请输入字典代码")
        form_layout.addRow("字典代码*:", self.dict_code_edit)
        
        # 字典名称
        self.dict_name_edit = QLineEdit()
        self.dict_name_edit.setPlaceholderText("请输入字典名称")
        form_layout.addRow("字典名称*:", self.dict_name_edit)
        
        # 父节点代码（仅在新增时显示）
        if not self.is_edit and self.parent_code:
            self.parent_code_edit = QLineEdit()
            self.parent_code_edit.setText(self.parent_code)
            self.parent_code_edit.setReadOnly(True)
            form_layout.addRow("父节点代码:", self.parent_code_edit)
        
        # 排序
        self.sort_order_spin = QSpinBox()
        self.sort_order_spin.setRange(0, 9999)
        self.sort_order_spin.setValue(0)
        form_layout.addRow("排序:", self.sort_order_spin)
        
        # 系统字典
        self.is_system_check = QCheckBox("系统字典")
        form_layout.addRow("系统字典:", self.is_system_check)
        
        # 描述
        self.description_edit = QTextEdit()
        self.description_edit.setPlaceholderText("请输入描述信息")
        self.description_edit.setMaximumHeight(100)
        form_layout.addRow("描述:", self.description_edit)
        
        layout.addLayout(form_layout)
        
        return widget
    
    def load_dictionary_data(self):
        """加载字典数据"""
        try:
            dictionary = self.service.get_dictionary_by_id(self.dict_id)
            if not dictionary:
                self.show_error_message("错误", "字典数据不存在")
                return
            
            # 填充表单数据
            self.dict_type_combo.setCurrentText(dictionary.get('dict_type', ''))
            self.dict_code_edit.setText(dictionary.get('dict_code', ''))
            self.dict_name_edit.setText(dictionary.get('dict_name', ''))
            self.sort_order_spin.setValue(dictionary.get('sort_order', 0))
            self.is_system_check.setChecked(dictionary.get('is_system', False))
            self.description_edit.setText(dictionary.get('description', ''))
            
            # 编辑模式下字典代码只读
            self.dict_code_edit.setReadOnly(True)
            
        except Exception as e:
            logger.error(f"加载字典数据失败: {e}")
            self.show_error_message("错误", f"加载数据失败: {str(e)}")
    
    def get_form_data(self) -> Dict[str, Any]:
        """获取表单数据"""
        data = {
            'dict_name': self.dict_name_edit.text().strip(),
            'dict_code': self.dict_code_edit.text().strip(),
            'sort_order': self.sort_order_spin.value(),
            'is_system': self.is_system_check.isChecked(),
            'description': self.description_edit.toPlainText().strip()
        }
        
        # 新增时包含字典类型
        if not self.is_edit:
            data['dict_type'] = self.dict_type_combo.currentText()
        
        # 新增且有父节点时包含父节点代码
        if not self.is_edit and hasattr(self, 'parent_code_edit'):
            data['parent_code'] = self.parent_code_edit.text().strip()
        
        return data
    
    def validate_form_data(self) -> tuple[bool, str]:
        """验证表单数据"""
        data = self.get_form_data()
        
        # 必填字段验证
        required_fields = ['dict_name', 'dict_code']
        if not self.is_edit:
            required_fields.append('dict_type')
        
        for field in required_fields:
            if not data.get(field):
                field_name = {
                    'dict_name': '字典名称',
                    'dict_code': '字典代码',
                    'dict_type': '字典类型'
                }.get(field, field)
                return False, f"{field_name}不能为空"
        
        # 字典代码格式验证
        dict_code = data['dict_code']
        if not dict_code.replace('_', '').isalnum():
            return False, "字典代码只能包含字母、数字和下划线"
        
        return True, ""
    
    def accept_data(self):
        """接受数据"""
        try:
            # 验证表单数据
            is_valid, error_msg = self.validate_form_data()
            if not is_valid:
                self.show_error_message("验证失败", error_msg)
                return
            
            # 获取表单数据
            data = self.get_form_data()
            
            # 保存或更新字典
            if self.is_edit:
                result = self.service.update_dictionary(self.dict_id, data)
            else:
                result = self.service.create_dictionary(data)
            
            if result['success']:
                self.show_success_message("成功", result['message'])
                self.dictionary_saved.emit(result.get('dict_id', ''))
                super().accept_data()
            else:
                self.show_error_message("失败", result['message'])
                
        except Exception as e:
            logger.error(f"保存字典失败: {e}")
            self.show_error_message("错误", f"保存失败: {str(e)}")